<template>
  <div class="app-container">
    <el-row>
      <el-col :lg="15">
        <el-form ref="form" :model="form" :rules="rules" label-position="top" style="padding-right: 100px;">
          <el-form-item label="文档名称" prop="doc_title">
            <el-input v-model="form.doc_title">
              <template slot="prepend">
                <span v-for="level in levels" :key="level.doc_id">{{ level.doc_title }} / </span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="MessageType" prop="message_type">
            <el-input v-model="form.message_type" />
          </el-form-item>
          <el-form-item label="关联表" prop="tables">
            <el-select v-model="form.tables" filterable placeholder="请选择关联表" multiple style="width: 100%" :filter-method="filter">
              <el-option
                v-for="item in tables"
                :key="item.table_name"
                :label="item.engine"
                :value="item.table_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="参数" prop="params">
            <el-tabs type="border-card">
              <el-tab-pane label="JSON" class="tab">
                <el-input v-model="form.params" type="textarea" :rows="10" />
              </el-tab-pane>
              <el-tab-pane label="参数说明" class="tab">
                <api-table
                  name="params"
                  :data="tableData_params"
                  style="width: 100%;margin-bottom: 20px;"
                />
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
          <el-form-item label="返回值" prop="returns">
            <el-tabs type="border-card">
              <el-tab-pane label="JSON" class="tab">
                <el-input v-model="form.returns" type="textarea" :rows="10" />
              </el-tab-pane>
              <el-tab-pane label="返回值说明" class="tab">
                <api-table
                  name="results"
                  :data="tableData_results"
                  style="width: 100%;margin-bottom: 20px;"
                />
              </el-tab-pane>
            </el-tabs>
          </el-form-item>
          <el-form-item label="更新信息" prop="message">
            <el-input v-model="form.message" placeholder="请输入更新信息" />
          </el-form-item>
          <el-form-item>
            <el-button :loading="test_loading" type="primary" @click="test">测试</el-button>
            <el-button v-show="!!auth" :loading="sure_loading" type="primary" @click="submitForm">{{ doc_id?'更新':'保存' }}</el-button>
            <el-button
              v-clipboard:copy="export_markdown()"
              v-clipboard:success="onCopy"
              v-clipboard:error="onError"
            >导出Markdown</el-button>
            <el-button @click="generator">表单生成器</el-button>
            <el-button @click="goback">取消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :lg="9">
        <el-card v-show="doc_id" class="box-card" style="margin-right: 100px;">
          <div slot="header" class="clearfix">
            <span>文档动态</span>
            <el-button v-show="auth==='developer'" type="text" icon="el-icon-plus" style="float: right; padding: 3px 0;color: #f56c6c" @click="make_question">添加问题</el-button>
          </div>
          <div v-for="o in logs" :key="o.edit_time" class="card-content">
            <div class="bottom clearfix">
              <span style="color: #409EFF;">{{ o.editor }}</span>
              <el-tooltip
                v-show="!!o.params"
                v-clipboard:copy="o.params"
                v-clipboard:success="onCopy"
                v-clipboard:error="onError"
                class="item"
                effect="dark"
                content="拷贝参数"
                placement="right"
              >
                <i class="el-icon-document-copy " style="color: #409EFF;cursor: pointer;" />
              </el-tooltip>
              <span class="button">{{ o.edit_time_display }}</span>
              <span v-show="o.state === 0" class="button" style="color:red;margin-right: 10px;cursor:pointer" @click="to_change_state(o)">未解决</span>
              <span v-show="o.state === 1" class="button" style="color:#67C23A;margin-right: 10px;">已解决</span>
              <span v-show="o.state === 2" class="button" style="color:#409EFF;margin-right: 10px;cursor:pointer" @click="to_change_state(o)">{{ auth==='developer'?'确认已解决':'等待确认' }}</span>
            </div>
            <div style="font-size: 14px;margin-top: 14px;white-space:normal; word-break:break-all;overflow:hidden;">{{ o.message }}</div>
            <el-divider class="divider" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <make-question :visible="make_question_display" @dialog-close="make_question_display = false" @dialog-sure="dialog_sure" />
  </div>
</template>

<script>
import { get, set } from '@/utils/storage'
import apiTable from '../components/api-table'
import { test_api, add, find_one_api, edit, change_state } from '../api'
import tree_data from '@/utils/tree-data'
import keep_data from '../atom/keep-data'
import makeQuestion from '../components/make-question'
import markdown from '@/utils/markdwon'
import { take_array } from '@/utils/keep-data'

export default {
  components: {
    apiTable,
    makeQuestion
  },
  data: function() {
    const validate_params = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入请求参数'))
      } else {
        try {
          JSON.parse(value)
          callback()
        } catch (error) {
          callback(new Error('请确保参数为JSON格式'))
        }
      }
    }
    return {
      tables: [],
      levels: [],
      logs: [],
      form: {
        doc_title: '',
        message_type: '',
        tables: [],
        params: '',
        returns: '',
        message: ''
      },
      rules: {
        doc_title: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        message_type: [{ required: true, message: '请输入MessageType', trigger: 'blur' }],
        params: [{ required: true, trigger: 'blur', validator: validate_params }],
        message: [{ required: true, message: '请输入更新日志', trigger: 'blur' }]
      },
      results: {
        request: [],
        response: []
      },
      tableData_params: [],
      tableData_results: [],
      test_loading: false,
      sure_loading: false,
      doc_id: '',
      auth: '',
      make_question_display: false
    }
  },
  created() {
    this.render_level()
    this.render_tables()
    this.render_form()
  },
  methods: {
    render_level() {
      const params = this.$route.params
      const doc_id = this.$route.query.doc_id

      if (JSON.stringify(params) === '{}' && !doc_id) {
        this.$router.replace({ path: '/' })
        return
      }
      this.levels = params.levels
      this.doc_id = this.$route.query.doc_id
      this.auth = get('role')
    },
    render_tables() {
      const project_id = this.$route.params.project_id
      this.tables = JSON.parse(get(project_id))
    },
    render_form() {
      const doc_id = this.$route.query.doc_id
      if (doc_id) {
        this.form.message = ''
        find_one_api(doc_id).then((res) => {
          this.form.message_type = res.data.message_type
          this.form.doc_title = res.data.doc_title
          this.form.tables = JSON.parse(res.data.tables)
          this.form.params = JSON.stringify(JSON.parse(res.data.params), null, '\t')
          this.logs = res.logs
          this.update(res.params, res.returns, JSON.parse(res.data.returns))
        })
        return
      } else {
        this.form.message = '新建服务'
      }
    },
    filter(label) {
      if (!label) {
        this.render_tables()
      }
      this.tables = this.tables.filter((tab) => {
        const table_name = tab.table_name.toLowerCase()
        const engine = tab.engine.toLowerCase()
        const _label = label.toLowerCase()
        return table_name.indexOf(_label) !== -1 || engine.indexOf(_label) !== -1
      })
    },
    submitForm() {
      if (this.doc_id && !this.form.message) {
        this.$message({
          message: '请输入更新信息',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      //
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.form.returns) {
            this.$message({
              message: '请先点击测试按钮，对接口进行测试',
              type: 'error',
              duration: 2 * 1000
            })
            return
          }
          this.sure_loading = true
          // 保存之前会再测试一下接口，但是不再更新页面数据
          // this.testmodel().then((res) => {
          const levels = this.$route.params.levels
          const parent_id = levels[levels.length - 1].doc_id
          if (this.doc_id) {
            edit(this.doc_id, this.form.doc_title, this.form.message, this.form.tables, JSON.parse(this.form.params), JSON.parse(this.form.returns), this.tableData_params, this.tableData_results).then((res) => {
              this.sure_loading = false
              this.$router.back()
            })
            return
          }
          add(this.$route.params.project_id, this.$route.params.spaceid, this.$route.params.type, parent_id, this.form.doc_title, this.form.tables, this.form.message_type, JSON.parse(this.form.params), JSON.parse(this.form.returns), this.tableData_params, this.tableData_results).then((res) => {
            this.sure_loading = false
            this.$router.back()
          })
          // }).catch((err) => {
          //   this.sure_loading = false
          //   console.warn(err)
          //   this.$message({
          //     message: '服务出错，打开控制台查看具体信息',
          //     type: 'success',
          //     duration: 2 * 1000
          //   })
          //   return
          // })
        }
      })
    },
    goback() {
      this.$router.back()
    },
    test() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.test_loading = true
          this.testmodel().then((res) => {
            this.update(res.request, res.response, res.data)
            this.test_loading = false
          }).catch((err) => {
            this.test_loading = false
            console.warn(err)
            this.$message({
              message: '服务出错，打开控制台查看具体信息',
              type: 'success',
              duration: 2 * 1000
            })
          })
        }
      })
    },
    update(request_data, response_data, data) {
      const request = keep_data(this.tableData_params, request_data)
      const response = keep_data(this.tableData_results, response_data)
      this.tableData_params = tree_data(request, 'parent_id', 'prop_id')
      this.tableData_results = tree_data(response, 'parent_id', 'prop_id')
      this.form.returns = JSON.stringify(data, null, '\t')
    },
    testmodel() {
      const tables = this.form.tables
      const params = this.form.params
      const message_type = this.form.message_type
      const doc_title = this.form.doc_title
      const sessionid = get('sessionid')
      return test_api(sessionid, this.$route.params.project_id, doc_title, message_type, params, tables)
    },
    make_question() {
      this.make_question_display = true
    },
    dialog_sure() {
      this.make_question_display = false
    },
    onCopy: function(e) {
      this.$message({
        message: '拷贝成功',
        type: 'success',
        duration: 2 * 1000
      })
      return
    },
    onError: function(e) {
      alert('Failed to copy texts')
    },
    to_change_state(row) {
      const state = row.state
      const user = get('user_code')
      const role = get('role')
      if (role === 'developer' && state === 0) {
        this.$message({
          message: '请通知开发者解决',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      } else if (role === 'maintainer' && state === 2) {
        this.$message({
          message: '请通知使用者确认',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      this.$confirm((() => {
        if (state === 0) {
          return '已解决？'
        } else if (state === 2) {
          return '确认已解决？'
        }
      })(), {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((ret) => {
        // 用户确认
        const _state = (() => {
          if (state === 0) {
            return '2'
          } else if (state === 2) {
            return '1'
          }
        })()
        change_state(row.question_id, _state, user).then(() => {
          this.render_form()
        })
      }).catch(() => {
        // 用户取消
      })
    },
    // 导出markdwon
    export_markdown() {
      // 文档名称，MessageType, 参数, 返回值
      const res = markdown(this.form.doc_title, this.form.message_type, this.form.params, this.tableData_params, this.form.returns, this.tableData_results)
      return res
    },
    generator() {
      const f1 = Array.from(take_array(this.tableData_params, new Map()).values()).filter((i) => {
        return i.note
      }).map((j) => {
        return {
          label: j.note,
          value: j.prop
        }
      })
      const f2 = Array.from(take_array(this.tableData_results, new Map()).values()).filter((i) => {
        return i.note
      }).map((j) => {
        return {
          label: j.note,
          value: j.prop
        }
      })
      set('filelds', JSON.stringify(f1.concat(f2)))
      window.open('http://192.168.1.238/form-generator', '_blank')
    }
  }
}
</script>

<style lang="scss" scoped>

.tab {
  input {
    height: 100%;
  }
}
.card-content {
  margin-bottom: 0;
  &:last-child {
    .divider {
      display: none;
    }
  }
}

  .button {
    padding: 0;
    float: right;
    color: #409EFF;
    font-size: 14px;
  }

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}
</style>
